<template>
  <view class="video-container">
    <swiper class="video-swiper" :vertical="true" :circular="false" @change="handleSwiperChange" :current="currentIndex" :duration="300">
      <swiper-item v-for="(item, index) in videoList" :key="index">
        <view class="swiper-item">
          <video
            class="video-player"
            :id="'video-' + index"
            :src="item.file"
            object-fit="contain"
            :autoplay="true"
            :loop="true"
            :controls="false"
            :show-center-play-btn="false"
            @play="onVideoPlay(index)"
            @pause="onVideoPause(index)"
            @ended="onVideoEnded(index)"
            @error="onVideoError(index)"
          ></video>

          <!-- 播放按钮 -->
          <view class="play-btn" v-if="currentIndex === index && !isPlaying" @click="togglePlay(index)">
            <text class="play-icon">▶</text>
          </view>
        </view>
      </swiper-item>
    </swiper>

    <!-- 加载提示 -->
    <view class="loading" v-if="isLoading">
      <text>加载中...</text>
    </view>
  </view>
</template>

<script>
  export default {
    props: {
      // 可以接收外部传入的视频列表
      initialVideoList: {
        type: Array,
        default: () => [],
      },
    },

    data() {
      return {
        videoList: this.initialVideoList || null,
        currentIndex: 0,
        isPlaying: false,
        isLoading: false,
        videoContexts: [],
      };
    },

    created() {
      // 如果没有传入视频列表，则获取视频列表
      if (!this.videoList || this.videoList.length === 0) {
        this.getVideoList();
      } else {
        this.$nextTick(() => {
          this.initVideoContexts();
        });
      }
    },

    mounted() {
      // 确保视频上下文初始化
      this.$nextTick(() => {
        this.initVideoContexts();

        // 延迟自动播放第一个视频
        setTimeout(() => {
          this.playCurrentVideo();
        }, 500);
      });
    },

    beforeDestroy() {
      // 停止所有视频
      this.pauseAllVideos();
    },

    methods: {
      // 获取视频列表
      getVideoList() {
        let params = {};

        this.isLoading = true;
        uni.request({
          url: 'https://emp.emeipaiglobal.com/api/live/videolist', // 替换为实际的API地址
          method: 'GET',
          data: params,
          header: {
            token: uni.getStorageSync('token') || '',
            'Content-Type': 'application/json',
          },
          success: (res) => {
            if (res.statusCode === 200 && res.data) {
              const response = res.data;
              if (response.code === 1 && response.data) {
                console.log('获取视频列表成功:', response.data.data);
                this.videoList = response.data.data;

                // 在获取视频列表成功后初始化视频上下文
                this.$nextTick(() => {
                  this.initVideoContexts();

                  // 延迟自动播放第一个视频
                  setTimeout(() => {
                    this.playCurrentVideo();
                  }, 500);
                });
              }
            }
            this.isLoading = false;
          },
          fail: (err) => {
            console.error('获取视频列表失败:', err);
            this.isLoading = false;
          },
          complete: () => {
            // 请求完成时的处理（可选）
          },
        });
      },

      // 初始化视频上下文
      initVideoContexts() {
        if (!this.videoList) return;
        console.log('初始化视频上下文，视频列表长度:', this.videoList.length);
        this.videoContexts = this.videoList.map((_, index) => {
          const videoContext = uni.createVideoContext(`video-${index}`, this);
          console.log(`创建视频上下文 ${index}:`, videoContext);
          return videoContext;
        });
      },

      // 播放当前视频
      playCurrentVideo() {
        if (this.videoContexts[this.currentIndex]) {
          // 确保视频上下文存在并调用play方法
          this.videoContexts[this.currentIndex].play();
          this.isPlaying = true;
          console.log('播放视频:', this.currentIndex);
        } else {
          console.error('视频上下文不存在:', this.currentIndex);
        }
      },

      // 暂停所有视频
      pauseAllVideos() {
        this.videoContexts.forEach((context) => {
          context && context.pause();
        });
        this.isPlaying = false;
      },

      // 切换播放/暂停
      togglePlay(index) {
        if (this.isPlaying) {
          this.pauseAllVideos();
        } else {
          this.playCurrentVideo();
        }
      },

      // 轮播切换事件
      handleSwiperChange(e) {
        const index = e.detail.current;
        console.log('轮播切换到:', index);
        this.pauseAllVideos();
        this.currentIndex = index;

        // 确保DOM更新后再播放视频
        this.$nextTick(() => {
          setTimeout(() => {
            this.playCurrentVideo();
          }, 300);
        });

        // 触发切换事件，通知父组件
        this.$emit('change', index);
      },

      // 视频播放事件
      onVideoPlay(index) {
        this.isPlaying = true;
        this.$emit('play', index);
      },

      // 视频暂停事件
      onVideoPause(index) {
        this.isPlaying = false;
        this.$emit('pause', index);
      },

      // 视频结束事件
      onVideoEnded(index) {
        // 循环播放当前视频
        if (this.videoContexts[index]) {
          this.videoContexts[index].seek(0);
          this.videoContexts[index].play();
        }
        this.$emit('ended', index);
      },

      // 视频错误事件
      onVideoError(index) {
        console.error(`视频${index}播放出错`);
        this.isPlaying = false;
        this.$emit('error', index, '视频播放出错');
      },

      // 提供给父组件的方法
      playVideo(index) {
        if (index >= 0 && index < this.videoList.length) {
          this.currentIndex = index;
          this.playCurrentVideo();
        }
      },

      pauseVideo(index) {
        if (index >= 0 && index < this.videoList.length) {
          this.pauseAllVideos();
        }
      },
    },
  };
</script>

<style lang="scss" scoped>
  .video-container {
    position: relative;
    width: 750rpx; /* 替换100vw，使用rpx单位 */
    height: 1334rpx; /* 替换100vh，使用rpx单位 */
    background-color: #000;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .video-swiper {
    flex: 1;
    width: 750rpx; /* 替换百分比 */
    height: 1334rpx; /* 替换百分比 */
  }

  .swiper-item {
    position: relative;
    width: 750rpx; /* 替换百分比 */
    height: 1334rpx; /* 替换百分比 */
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #000;
  }

  .video-player {
    width: 750rpx; /* 替换百分比 */
    height: 1334rpx; /* 替换百分比 */
    display: flex; /* 替换block为flex */
    object-fit: contain;
    /* 改为contain模式，保持视频原比例 */
  }

  .play-btn {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 10;

    .play-icon {
      font-size: 80rpx;
      color: rgba(255, 255, 255, 0.8);
    }
  }

  .loading {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    color: #fff;
    font-size: 28rpx;
  }
</style>
